
package hackathon.techbooster.tanabata;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

public class ShowListActivity extends Activity {
    private static final String TAG = ShowListActivity.class.getSimpleName();

    public static final int DIALOG_SEARCH = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_list);
        try {
            final String id = PreferenceUtils.encodeUrl(PreferenceUtils.getCreatedId(this));

            Log.d(TAG, "url=" + getString(R.string.list_url, id));
            new JsonLoadAsync().execute(getString(R.string.list_url, id));
        } catch (UnsupportedEncodingException e) {
            Toast.makeText(this, R.string.error_change_char, Toast.LENGTH_SHORT).show();
        }

        // Twitter連携
        if (getIntent().getBooleanExtra(PreferenceUtils.KEY_TWITTER, false)) {
            String tweet = getIntent().getStringExtra(PreferenceUtils.KEY_TWEET_MESSAGE);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, tweet);
            try {
                startActivity(intent);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(this, "client not found", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            BambooView view = (BambooView) findViewById(R.id.bamboo);
            if (view.isSettings(event)) {
                showDialog(DIALOG_SEARCH);
                return false;
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        AlertDialog.Builder builder;

        if (id == DIALOG_SEARCH) {
            builder = new AlertDialog.Builder(this);
            final View view = inflater.inflate(R.layout.dialog_search,
                    (ViewGroup) findViewById(R.id.layout_root));

            builder.setView(view)
                    .setPositiveButton(R.string.btn_search, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                final String user = PreferenceUtils.encodeUrl(((EditText) view
                                        .findViewById(R.id.user)).getText().toString().trim());

                                if( !user.equals("")) {
                                    ((BambooView)findViewById(R.id.bamboo)).clear();
                                    Log.d(TAG, "url=" + getString(R.string.search_url, user));
                                    new JsonLoadAsync().execute(getString(R.string.search_url, user));
                                }
                                dialog.dismiss();
                            } catch (UnsupportedEncodingException e) {
                                Toast.makeText(getApplicationContext(), R.string.error_change_char,
                                        Toast.LENGTH_SHORT).show();
                            }

                        }
                    })
                    .setNegativeButton(R.string.btn_cansel, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

            dialog = builder.create();
        }
        return dialog;
    }

    public class JsonLoadAsync extends AsyncTask<String, Void, String> {

        public JsonLoadAsync() {
            findViewById(R.id.progressbar_area).setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... url) {
            String htmlData;
            try {
                htmlData = getHttpData(url[0]);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            return htmlData;
        }

        @Override
        protected void onPostExecute(String result) {
            findViewById(R.id.progressbar_area).setVisibility(View.GONE);
            super.onPostExecute(result);
            if (result == null || result.equals("")) {
                result = PreferenceUtils.getJson(getApplicationContext());
                if (result.equals("")) {
                    Toast.makeText(getApplicationContext(), R.string.error_get_data,
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), R.string.error_get_data_offline,
                            Toast.LENGTH_LONG).show();
                    setJsonData(result);
                }
            } else {
                PreferenceUtils.setJson(getApplicationContext(), result);
                setJsonData(result);
            }
        }

        private String getHttpData(String url) throws IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpGet request = new HttpGet(url);
            // HttpResponse httpResponse = httpClient.execute(request);

            String result = "";
            try {
                result = httpClient.execute(request, new ResponseHandler<String>() {
                    @Override
                    public String handleResponse(HttpResponse response)
                            throws ClientProtocolException, IOException {
                        // response.getStatusLine().getStatusCode()でレスポンスコードを判定する。
                        // 正常に通信できた場合、HttpStatus.SC_OK（HTTP 200）となる。
                        switch (response.getStatusLine().getStatusCode()) {
                            case HttpStatus.SC_OK:
                                // レスポンスデータを文字列として取得する。
                                // byte[]として読み出したいときはEntityUtils.toByteArray()を使う。
                                return EntityUtils.toString(response.getEntity(), "UTF-8");
                            default:
                                throw new IOException("status error:status="
                                        + response.getStatusLine().getStatusCode());
                        }

                    }
                });

            } catch (ClientProtocolException e) {
                throw new IOException("ClientProtocolException" + e.getStackTrace());
            } finally {
                // ここではfinallyでshutdown()しているが、HttpClientを使い回す場合は、
                // 適切なところで行うこと。当然だがshutdown()したインスタンスは通信できなくなる。
                httpClient.getConnectionManager().shutdown();
            }

            return result;
        }
    }

    private void setJsonData(String json) {
        BambooView view = (BambooView) findViewById(R.id.bamboo);
        try {
            JSONArray datas = new JSONArray(json);
            view.setBaseData(datas);
            int idx = 0;
            for (int cnt = 0; cnt < datas.length(); cnt++) {
                JSONObject data = datas.getJSONObject(cnt);
                String id = data.getString(PreferenceUtils.JSON_ID);
                if (!id.equals("-1")) {
                    view.setBitmap(idx);
                }
                if (++idx >= 10) {
                    break;
                }
            }
            view.invalidate();
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), R.string.error_data_format, Toast.LENGTH_SHORT)
                    .show();
            e.printStackTrace();
            Log.e(TAG, "data=" + json);
        }

    }
}
